#!/usr/bin/env bash
# phpstorm

if [[ -z "${c_phpstorm}" ]]; then
    f_info 'phpstorm: not install';
    echo > /dev/null;  return;
fi;

# instsll
ins="${INS}/phpstorm";  ov=`cat "${ins}/.version" 2>/dev/null`;
if [[ "${ov}" = "${c_phpstorm}" ]]; then f_info "phpstorm: has v${c_phpstorm}";
else
    f_wait "phpstorm: v${c_phpstorm}";  n="phpstorm-${c_phpstorm}.tgz";
    url="https://download.jetbrains.com.cn/webide/PhpStorm-${c_phpstorm}.tar.gz";
    f_down 'phpstorm' "${n}" "${url}";  cd "${INS}" || f_fail 'phpstorm: cd to INS';
    rm -rf phpstorm* || f_fail 'phpstorm: del old ins';
    rm -rf PhpStorm* || f_fail 'phpstorm: del old src';
    tar zxf "${TMP}/${n}" || f_fail 'phpstorm: tar zxf';
    mv "PhpStorm-"* "${ins}" || f_fail 'phpstorm: mv source';
    echo "${c_phpstorm}" > "${ins}/.version" || f_fail 'phpstorm: save version';
fi;

# users
run=$(cat "${RUN}/file/ide/php/run.sh");
ini=$(cat "${RUN}/file/ide/php/config.ini");
srv=$(cat "${RUN}/file/ide/php/src.service");
for v in ${c_phpstorm_srv}; do
    f_wait "phpstorm: user ${v}";  u=${v%:*};  p=${v#*:};  
    tar="${DIR}/serv/ide-${u}-php.service";
    cfg="/home/${u}/.projector/configs/php";  own="${u}:${u}";
    mkdir -p "${cfg}" || f_fail "phpstorm: ${u} mkdir config";
    echo "${run//\{PORT\}/${p}}" > "${cfg}/run.sh" || f_fail "phpstorm: ${u} run.sh";
    echo "${ini//\{PORT\}/${p}}" > "${cfg}/config.ini" || f_fail "phpstorm: ${u} config.ini";
    echo "${srv//\{USER\}/${u}}" > "${tar}" || f_fail "phpstorm: ${u} service";
    f_link "${tar}" "/usr/lib/systemd/system/ide-${u}-php.service";
    f_mode "${cfg}" "755" - "${u}";  f_auto "phpstorm.${u}" "ide-${u}-php" 1;
    systemctl restart "ide-${u}-php" || f_fail "phpstorm: restart ${u}";
done;
